package com.demo.zlb.sso.login.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.zlb.sso.login.constants.Constants;
import com.demo.zlb.sso.login.utils.IrsSignRes;
import com.demo.zlb.sso.login.utils.IrsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @author jie.chen
 * @date 2022-03-30 15:49
 */
@Component
public class AuthService {


    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    private RestTemplate restTemplate;

    @PostConstruct
    void init() {
        restTemplate = restTemplateBuilder.build();
    }


    public String getTokenByTicketId(String ticketId) {

        HttpHeaders headers = getHttpHeaders(Constants.ACCESS_TOKEN_URL);
        JSONObject body = new JSONObject();
        body.put("appId", Constants.APP_ID);
        body.put("ticketId", ticketId);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(Constants.ACCESS_TOKEN_URL, request, String.class);
        return checkResponse(stringResponseEntity).getJSONObject("data").getString("accessToken");
    }


    public JSONObject getUserInfoByToken(String accessToken) {
        HttpHeaders headers = getHttpHeaders(Constants.GET_USER_INFO_URL);
        JSONObject body = new JSONObject();
        body.put("token", accessToken);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(Constants.GET_USER_INFO_URL, request, String.class);
        return checkResponse(stringResponseEntity).getJSONObject("data");
    }

    private JSONObject checkResponse(ResponseEntity<String> stringResponseEntity) {
        if (!stringResponseEntity.getStatusCode().is2xxSuccessful()) {
            //请求失败
            throw new RuntimeException("status:" + stringResponseEntity.getStatusCodeValue() + " " + stringResponseEntity.getBody());
        }
        JSONObject result = JSON.parseObject(stringResponseEntity.getBody());
        if (result.containsKey("errorCode") && result.getString("errorCode") != null && !result.getBooleanValue("success")) {
            //业务错误
            throw new RuntimeException(result.toString());
        }
        return result;
    }

    private HttpHeaders getHttpHeaders(String url) {
        IrsSignRes res = IrsUtils.sign(url, "POST");

        HttpHeaders headers = new HttpHeaders();
        headers.add(Constants.X_BG_HMAC_ACCESS_KEY, res.getAccessKey());
        headers.add(Constants.X_BG_HMAC_ALGORITHM, res.getAlgorithm());
        headers.add(Constants.X_BG_HMAC_SIGNATURE, res.getSignature());
        headers.add(Constants.X_BG_DATE_TIME, res.getDateTime());
        return headers;
    }

}
